#!/usr/bin/env python
# coding: utf-8

# ## 上周小结：
# 
# > A. 
# > B.
# 
# ## 本代码有如下练习：
# 
# > 1.[地理编码](https://lbs.amap.com/api/webservice/guide/api/georegeo)
# 
# > 2.[路径规划](https://lbs.amap.com/api/webservice/guide/api/direction)
# 
# > 3.[行政区域查询](https://lbs.amap.com/api/webservice/guide/api/district)
# 
# > 4.[搜素POI](https://lbs.amap.com/api/webservice/guide/api/search)
# 
# > 5.[IP定位](https://lbs.amap.com/api/webservice/guide/api/ipconfig)
# 
# > 6.[静态地图](https://lbs.amap.com/api/webservice/guide/api/staticmaps)
# 
# > 7.[坐标转换](https://lbs.amap.com/api/webservice/guide/api/convert)
# 
# > 8.[天气查询](https://lbs.amap.com/api/webservice/guide/api/weatherinfo)
# 
# > 9.[输入提示](https://lbs.amap.com/api/webservice/guide/api/inputtips)
# 
# > 10.[交通态势](https://lbs.amap.com/api/webservice/guide/api/trafficstatus)

# ### 准备工作

# In[3]:


import requests, json
import pandas as pd
h_key = "9283a3ae76c2742c8a55d9d6e6c75a24"


# ### 地理编码
# > 1.[地理编码](https://lbs.amap.com/api/webservice/guide/api/georegeo)
# >> 1.1 结构化地址的定义： 首先，地址肯定是一串字符，内含国家、省份、城市、区县、城镇、乡村、街道、门牌号码、屋邨、大厦等建筑物名称。按照由大区域名称到小区域名称组合在一起的字符。一个有效的地址应该是独一无二的。注意：针对大陆、港、澳地区的地理编码转换时可以将国家信息选择性的忽略，但省、市、城镇等级别的地址构成是不能忽略的。暂时不支持返回台湾省的详细地址信息
# 
# >> 1.2 url:	https://restapi.amap.com/v3/geocode/geo?parameters
# 
# >> 1.3 request.get
# 
# >> 1.4 参数：key,address

# In[4]:


# A-1
address = "广东省广州市中山大学南方学院"
url_geocode="https://restapi.amap.com/v3/geocode/geo?parameters"
params_geocode ={
    "key":h_key,
    "address":address
}
response = requests.get(url=url_geocode,params=params_geocode)


# In[5]:


response


# In[6]:


response.json()


# In[7]:


中大南方_location=response.json()['geocodes'][0]['location']
中大南方_location


# In[8]:


def geocode(address,city=None,batch=None,sig=None):
    """获取地理编码"""
    url = 'https://restapi.amap.com/v3/geocode/geo?parameters'
    params={
        'key': h_key,
        'address':address,
        'city':city,
        'batch':batch,
        'sig':sig,       
    }
    response = requests.get(url,params=params)
    results = response.json()
    return results


# In[9]:


天河城_location=geocode('广东省广州市天河城')['geocodes'][0]['location']
天河城_location


# ### 逆地理编码
# * url:https://restapi.amap.com/v3/geocode/regeo?parameters

# In[10]:


def regeo(key,location,extensions="base",poitype=None,radius=None,roadlevel=None):
    """ 高德API逆地理编码获取 """
    url ='https://restapi.amap.com/v3/geocode/regeo?parameters'
    params={
        "key":h_key,
        "location":location,
        "extensions":extensions,
        "poitype":poitype,
        "radius":radius,
        "roadlevel":roadlevel

    }
    r=requests.get(url,params=params)
    return r.json()


# In[11]:


regeo(key=h_key,location=中大南方_location,radius=3000)


# In[12]:


url_regeo ='https://restapi.amap.com/v3/geocode/regeo?parameters'
params_regeo={
    "key":h_key,
    "location":中大南方_location,
    "extensions":"all"
}
r=requests.get(url=url_regeo,params=params_regeo)


# In[13]:


results=r.json()
results


# In[14]:


# 显示道路信息
pd.json_normalize(results['regeocode']['roads'])


# ### 路径规划
# > 2.[路径规划](https://lbs.amap.com/api/webservice/guide/api/direction)
# 
# >> 2.1 路径规划API是一套以HTTP形式提供的步行、公交、驾车查询及行驶距离计算接口，返回JSON 或 XML格式的查询数据，用于实现路径规划功能的开发。 
# 
# >> 2.2 
# * 步行url:https://restapi.amap.com/v3/direction/walking?parameters
# * 公交url:https://restapi.amap.com/v3/direction/transit/integrated?parameters
# * 驾车url: https://restapi.amap.com/v3/direction/driving?parameters
# 
# >> 2.3 request.get
# 
# >> 2.4 参数：key,origin, destination
# 
# >> 2.5 应用：根据用户需求的行驶条件规划路径

# In[15]:


# 准备起始点和终点
start_add="广东省广州市中山大学南方学院"
stop_add="广东省广州市龙岗"


# In[16]:


# 函数
def geocode(key,address,city=None):
    """ 高德API地理编码获取 """
    url="https://restapi.amap.com/v3/direction/walking?parameters"
    params_geocode ={
    "key":h_key,
    "address":address
    }
    response = requests.get(url=url_geocode,params=params_geocode)
    results=response.json()['geocodes'][0]['location']
    return results


# In[17]:


results_起始点=geocode(h_key,start_add)
results_起始点


# In[18]:


results_终点=geocode(h_key,stop_add)
results_终点


# In[19]:


# 起点坐标
address = "广东省广州市中山大学南方学院"
url_geocode="https://restapi.amap.com/v3/direction/walking?parameters"
params_geocode ={
    "key":h_key,
    "address":address
}
response = requests.get(url=url_geocode,params=params_geocode)


# In[20]:


# 终点坐标
address = "广东省广州市龙岗"
url_geocode="https://restapi.amap.com/v3/direction/walking?parameters"
params_geocode ={
    "key":h_key,
    "address":address
}
response = requests.get(url=url_geocode,params=params_geocode)


# #### 步行规划
# * url:https://restapi.amap.com/v3/direction/walking?parameters

# In[21]:


url_walking = "https://restapi.amap.com/v3/direction/walking?parameters"
params_walking ={
    "key":h_key,
    "origin":results_起始点,
    "destination":results_终点
}
r = requests.get(url=url_walking,params=params_walking)


# In[22]:


r


# In[23]:


r.json()


# In[24]:


#期中测试：计算距离？1.里面的数据是什么格式？str->int 2.是不是要会list循环遍历？ 3.运算？


# In[25]:


r_distance=pd.json_normalize(r.json()['route']['paths'][0]['steps'])['distance'].to_list()
r_distance


# In[26]:


found={}
for i in r_distance:
    found.setdefault(i,0)
    found[i]+=1

len(found)


# In[27]:


found


# In[28]:


# 期中测试2：有多少个情况？每一个情况多少次？有多少个空的？请转换换成字典作为结果


# In[29]:


pd.json_normalize(r.json()['route']['paths'][0]['steps'])['orientation'].to_list()


# In[30]:


def walking(origin,destination):
    url="https://restapi.amap.com/v3/direction/walking?parameters"
    params={
        "key":h_key,
        "origin":origin,
        "destination":destination,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[31]:


results_步行=walking(results_起始点,results_终点)
results_步行


# #### 公交规划
# * url:https://restapi.amap.com/v3/direction/transit/integrated?parameters

# In[32]:


url_integrated = "https://restapi.amap.com/v3/direction/transit/integrated?parameters"
params_integrated ={
    "key":h_key,
    "origin":results_起始点,
    "destination":results_终点,
    "city":'广州'
}
r = requests.get(url=url_integrated,params=params_integrated)


# In[33]:


r


# In[34]:


r.json()


# In[35]:


def integrated(origin,destination,city,cityd=None,extensions='base',strategy=0,nightflag=0,date=None,time=None,sig=None):
    url="https://restapi.amap.com/v3/direction/transit/integrated?parameters"
    params={
        "key":h_key,
        "origin":origin,
        "destination":destination,
        "city":city,
        "cityd":cityd,
        "extensions":extensions,
        "strategy":strategy,
        "nightflag":nightflag,
        "date":date,
        "time":time,
        "sig":sig,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[36]:


results_公交=integrated(中大南方_location,天河城_location,"广州")
results_公交


# In[37]:


pd.json_normalize(results_公交['route']['transits'][0]['segments'][0]['bus']['buslines'][0]['via_stops'])


# #### 驾车规划
# * url:https://restapi.amap.com/v3/direction/driving?parameters

# In[38]:


url_driving = "https://restapi.amap.com/v3/direction/driving?parameters"
params_driving ={
    "key":h_key,
    "origin":results_起始点,
    "destination":results_终点,
    "city":'广州'
}
r = requests.get(url=url_driving,params=params_driving)


# In[39]:


r


# In[40]:


r.json()


# In[41]:


def driving(origin,destination,originid=None,destinationid=None,origintype=None,destinationtype=None,strategy=0,waypoints=None,avoidpolygons=None,avoidroad=None,province='粤',number=None,cartype=0,ferry=0,roadaggregation='false',nosteps=0,sig=None,extensions='base'):
    url="https://restapi.amap.com/v3/direction/driving?parameters"
    params={
        "key":h_key,
        "origin":origin,
        "destination":destination,
        "originid":originid,
        "destinationid":destinationid,
        "origintype":origintype,
        "destinationtype":destinationtype,
        "strategy":strategy,
        "waypoints":waypoints,
        "avoidpolygons":avoidpolygons,
        "avoidroad":avoidroad,
        "province":province,
        "number":number,
        "cartype":cartype,
        "ferry":ferry,
        "roadaggregation":roadaggregation,
        "nosteps":nosteps,
        "extensions":extensions,
        "sig":sig,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[42]:


results_驾车=driving(results_起始点,results_终点)
results_驾车


# In[43]:


pd.json_normalize(results_驾车['route']['paths'][0]['steps'])['instruction'].to_list()


# #### 骑车规划
# * url:https://restapi.amap.com/v4/direction/bicycling?parameters

# In[44]:


url_bicycling = "https://restapi.amap.com/v4/direction/bicycling?parameters"
params_bicycling ={
    "key":h_key,
    "origin":results_起始点,
    "destination":results_终点,
}
r = requests.get(url=url_bicycling,params=params_bicycling)


# In[45]:


r


# In[46]:


r.json()


# In[47]:


def bicycling(origin,destination):
    url="https://restapi.amap.com/v4/direction/bicycling?parameters"
    params={
        "key":h_key,
        "origin":origin,
        "destination":destination,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[48]:


results_骑车=bicycling(results_起始点,results_终点)
results_骑车


# In[49]:


pd.json_normalize(results_骑车['data']['paths'][0]['steps'])


# #### 货车规划
# * url:https://restapi.amap.com/v4/direction/truck?parameters

# In[50]:


url_truck = "https://restapi.amap.com/v4/direction/truck?parameters"
params_truck ={
    "key":h_key,
    "origin":results_起始点,
    "destination":results_终点,
    "size":1
}
r = requests.get(url=url_truck,params=params_truck)


# In[51]:


r


# In[52]:


r.json()


# In[53]:


def truck(origin,destination,size,originid=None,destinationid=None,origintype=None,destinationtype=None,diu=None,strategy=1,waypoints=None,height=None,width=None,load=None,weight=None,axis=None,province='粤',number=None,cartype=0,avoidpolygons=None,showpolyline=1,nosteps=0):
    url="https://restapi.amap.com/v4/direction/truck?parameters"
    params={
        "key":h_key,
        "origin":origin,
        "destination":destination,
        "size":size,
        "originid":originid,
        "destinationid":destinationid,
        "origintype":origintype,
        "destinationtype":destinationtype,
        "diu":diu,
        "strategy":strategy,
        "waypoints":waypoints,
        "height":height,
        "width":width,
        "load":load,
        "weight":weight,
        "axis":axis,
        "province":province,
        "number":number,
        "cartype":cartype,
        "avoidpolygons":avoidpolygons,
        "showpolyline":showpolyline,
        "nosteps":nosteps,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[54]:


results_货车=truck(results_起始点,results_终点,1)
results_货车


# In[55]:


pd.json_normalize(results_货车['data']['route']['paths'][0]['steps'])


# #### 测量距离
# * url:https://restapi.amap.com/v3/distance?parameters

# In[56]:


url_distance = "https://restapi.amap.com/v3/distance?parameters"
params_distance ={
    "key":h_key,
    "origin":results_起始点,
    "destination":results_终点,
    "type":1
}
r = requests.get(url=url_distance,params=params_distance)


# In[57]:


r


# In[58]:


r.json()


# In[59]:


def distance(origin,destination,type,sig=None):
    url="https://restapi.amap.com/v3/distance?parameters"
    params={
        "key":h_key,
        "origin":origin,
        "destination":destination,
        "type":type,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[60]:


results_距离=distance(results_起始点,results_终点,1)
results_距离


# ### 行政区域查询
# > 1.行政区域查询是一类简单的HTTP接口，根据用户输入的搜索条件可以帮助用户快速的查找特定的行政区域信息。
# 
# > 2.url:https://restapi.amap.com/v3/config/district?parameters
# 
# > 3.request.get
# 
# > 4.应用：查询省级市级等的不同等级城市

# In[61]:


url_district = "https://restapi.amap.com/v3/config/district?parameters"
params_district ={
    "key":h_key,
}
r = requests.get(url=url_district,params=params_district)


# In[62]:


r


# In[63]:


r.json()


# In[64]:


def district(keywords,subdistrict=None,page=None,offset=None,extensions='base',):
    url="https://restapi.amap.com/v3/config/district?parameters"
    params={
        "key":h_key,
        "keywords":keywords,
        "subdistrict":subdistrict,
        "page":page,
        "offset":offset,
        "extensions":extensions,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[65]:


results_行政区域查询=district('广东',3)
results_行政区域查询


# In[66]:


pd.json_normalize(results_行政区域查询['districts'][0]['districts'])


# ### 搜索POI
# > 1.搜索服务API是一类简单的HTTP接口，提供多种查询POI信息的能力，其中包括关键字搜索、周边搜索、多边形搜索、ID查询四种筛选机制。
# 
# > 2.request.get
# 
# > 3.应用：根据关键字、地理位置、规定范围查找特定地点，弹出相关地点和附近地点

# #### 关键字搜素
# * url:	https://restapi.amap.com/v3/place/text?parameters

# In[67]:


url_text = "https://restapi.amap.com/v3/place/text?parameters"
params_text ={
    "key":h_key,
    "keywords":'东莞'
    
}
r = requests.get(url=url_text,params=params_text)


# In[68]:


r


# In[69]:


r.json()


# In[70]:


def text(keywords,types,city=None,citylimit=None,children=0,offset=None,page=None,extensions='base',sig=None):
    url="https://restapi.amap.com/v3/place/text?parameters"
    params={
        "key":h_key,
        "keywords":keywords,
        "types":types,
        "city":city,
        "citylimit":citylimit,
        "children":children,
        "offset":offset,
        "page":page,
        "extensions":extensions,
        "sig":sig,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[71]:


results_关键字搜素=text('美食','050203','东莞')
results_关键字搜素


# In[72]:


pd.json_normalize(results_关键字搜素['pois'])['name']


# #### 周边搜素
# * url:https://restapi.amap.com/v3/place/around?parameters 

# In[73]:


url_around = "https://restapi.amap.com/v3/place/around?parameters"
params_around ={
    "key":h_key,
    "location":中大南方_location
    
}
r = requests.get(url=url_around,params=params_around)


# In[74]:


r


# In[75]:


r.json()


# In[76]:


def around(location,keywords=None,types=None,city=None,radius=None,sortrule=None,offset=None,page=None,extensions='base',sig=None):
    url="https://restapi.amap.com/v3/place/around?parameters"
    params={
        "key":h_key,
        "location":location,
        "keywords":keywords,
        "types":types,
        "city":city,
        "radius":radius,
        "sortrule":sortrule,
        "offset":offset,
        "page":page,
        "extensions":extensions,
        "sig":sig,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[77]:


results_周边搜素=around(中大南方_location)
results_周边搜素


# In[78]:


pd.json_normalize(results_周边搜素['pois'])['name']


# #### 多边形搜素
# * url:https://restapi.amap.com/v3/place/polygon?parameters

# In[79]:


url_polygon = "https://restapi.amap.com/v3/place/polygon?parameters"
params_polygon ={
    "key":h_key,
    "polygon":'113.679287,23.632575 | 113.361200,23.124680'
}
r = requests.get(url=url_polygon,params=params_polygon)


# In[80]:


r


# In[81]:


r.json()


# In[82]:


def polygon(polygon,keywords=None,types=None,offset=None,page=None,extensions='base',sig=None):
    url="https://restapi.amap.com/v3/place/polygon?parameters"
    params={
        "key":h_key,
        "polygon":polygon,
        "keywords":keywords,
        "types":types,
        "offset":offset,
        "page":page,
        "extensions":extensions,
        "sig":sig,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[83]:


results_多边形搜素=polygon('113.679287,23.632575 | 113.361200,23.124680')
results_多边形搜素


# In[84]:


pd.json_normalize(results_周边搜素['pois'])


# #### ID查询
# * url:https://restapi.amap.com/v3/place/detail?parameters 

# In[85]:


url_detail = "https://restapi.amap.com/v3/place/detail?parameters"
params_detail ={
    "key":h_key,
    "id":'B0FFFAB6J2'
}
r = requests.get(url=url_detail,params=params_detail)


# In[86]:


r


# In[87]:


r.json()


# In[88]:


def detail(id,sig=None):
    url="https://restapi.amap.com/v3/place/detail?parameters"
    params={
        "key":h_key,
        "id":id,
        "sig":sig,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[89]:


results_ID查询=detail('B0FFFAB6J2')
results_ID查询


# In[90]:


pd.json_normalize(results_ID查询['pois'])


# ### IP定位
# > 1.IP定位是一个简单的HTTP接口，根据用户输入的IP地址，能够快速的帮用户定位IP的所在位置。
# 
# > 2.url:https://restapi.amap.com/v3/ip?parameters
# 
# > 3.request.get

# In[91]:


url_ip = "https://restapi.amap.com/v3/ip?parameters"
params_ip ={
    "key":h_key,
    "ip":'81.71.135.135'
}
r = requests.get(url=url_ip,params=params_ip)


# In[92]:


r


# In[93]:


r.json()


# In[94]:


def ip(ip,sig=None):
    url="https://restapi.amap.com/v3/ip?parameters"
    params={
        "key":h_key,
        "ip":ip,
        "sig":sig,
        "output":'json'
    }
    r=requests.get(url,params=params)
    results=r.json()
    return results


# In[95]:


results_ip定位=ip('81.71.135.135')
results_ip定位


# ### 静态地图
# >1. 静态地图服务通过返回一张地图图片响应HTTP请求，使用户能够将高德地图以图片形式嵌入自己的网页中。用户可以指定请求的地图位置、图片大小、以及在地图上添加覆盖物，如标签、标注、折线、多边形。
# 
# >2. url:https://restapi.amap.com/v3/staticmap?parameters
# 
# >3. requests.get
# 
# >4. key, location,zoom
# 
# >5. 应用：直接看到地图中的目标点，用户需要按地图来进行导航，得到不同尺寸的地图

# In[96]:


from PIL import Image
from io import BytesIO

def staticmap(location,zoom,size=None,scale=1,markers=None,labels=None,paths=None,traffic=0,sig=None):
    url="https://restapi.amap.com/v3/staticmap?parameters"
    params={
        "key":h_key,
        "location":location,
        "zoom":zoom,
        "size":size,
        "scale":scale,
        "markers":markers,
        "labels":labels,
        "paths":paths,
        "traffic":traffic,
        "sig":sig,
        "output":'json'
    }
    response = requests.get(url,params=params)
    data=Image.open(BytesIO(response.content))
    return data


# In[147]:


data_静态地图=staticmap(天河城_location,[1,17],'1024*1024')
data_静态地图


# ### 坐标转换
# >1. 坐标转换是一类简单的HTTP接口，能够将用户输入的非高德坐标（GPS坐标、mapbar坐标、baidu坐标）转换成高德坐标。
# 
# >2. url:https://restapi.amap.com/v3/assistant/coordinate/convert?parameters
# 
# >3. requests.get
# 
# >4. key,locations
# 
# >5. 应用：不同网站之间地址坐标的转换

# In[105]:


def convert(locations,coordsys=None,sig=None):
    url="https://restapi.amap.com/v3/assistant/coordinate/convert?parameters"
    params={
        "key":h_key,
        "locations":locations,
        "coordsys":coordsys,
        "sig":sig,
        "output":'json'
    }
    response=requests.get(url,params=params)
    results=response.json()
    return results


# In[106]:


location_baidu_中大南方=113.685752,23.638368


# In[111]:


results_坐标转换=convert(location_baidu_中大南方)
results_坐标转换


# ### 天气查询
# >1. 天气查询是一个简单的HTTP接口，根据用户输入的adcode，查询目标区域当前/未来的天气情况。
# 
# >2. url:https://restapi.amap.com/v3/weather/weatherInfo?parameters
# 
# >3. requests.get
# 
# >4. key,city
# 
# >5. 应用：天气查询APP

# In[123]:


def weatherInfo(city,extensions=None):
    url="https://restapi.amap.com/v3/weather/weatherInfo?parameters"
    params={
        "key":h_key,
        "city":city,
        "extensions":extensions,
        "output":'json'
    }
    response=requests.get(url,params=params)
    results=response.json()
    return results


# In[126]:


results_广州天气=weatherInfo(440100,'base')
results_广州天气


# ### 输入提示
# >1. 输入提示是一类简单的HTTP接口，提供根据用户输入的关键词查询返回建议列表。
# 
# >2. url:https://restapi.amap.com/v3/assistant/inputtips?parameters
# 
# >3. requests.get
# 
# >4. key,keywords
# 
# >5. 应用：搜索框的提示，按照最近搜索过的字词或被搜素最多次数的字词

# In[129]:


def inputtips(keywords,type=None,location=None,city=None,citylimit=None,datatype=all,sig=None):
    url="https://restapi.amap.com/v3/assistant/inputtips?parameters"
    params={
        "key":h_key,
        "keywords":keywords,
        "type":type,
        "location":location,
        "city":city,
        "citylimit":citylimit,
        "datatype":datatype,
        "sig":sig,
        "output":'json'
    }
    response=requests.get(url,params=params)
    results=response.json()
    return results


# In[141]:


results_输入提示=inputtips('麦当劳','050302',天河城_location,440100)
results_输入提示


# In[142]:


pd.json_normalize(results_输入提示['tips'])


# ### 交通态势
# >1. 交通态势是一类简单的HTTP接口，提供根据用户输入的内容能够返回希望查询的交通态势情况。
# 
# >2. url:https://restapi.amap.com/v3/traffic/status/rectangle?parameters
# 
# >3. requests.get
# 
# >4. key,rectangle
# 
# >5. 应用：实时获取交通实况，看是否有阻碍交通路线的因素

# In[143]:


def rectangle(rectangle,level=None,extensions='base',sig=None):
    url="https://restapi.amap.com/v3/traffic/status/rectangle?parameters"
    params={
        "key":h_key,
        "rectangle":rectangle,
        "level":level,
        "extensions":extensions,
        "sig":sig,
        "output":'json'
    }
    response=requests.get(url,params=params)
    results=response.json()
    return results


# In[146]:


results_交通态势=rectangle(中大南方_location,天河城_location)
results_交通态势


# In[ ]:




